package com.ecar.api.rest.driver;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;

import com.ecar.api.rest.AbstractResource;
import com.ecar.api.service.common.FlightService;
import com.ecar.api.service.common.ModelSetService;
import com.ecar.api.service.common.PriceCalculateService;
import com.ecar.api.service.driver.CarService;
import com.ecar.api.service.driver.ComplaintService;
import com.ecar.api.service.driver.DriverService;
import com.ecar.api.service.driver.IdeaService;
import com.ecar.api.service.order.OrderPriceDetailService;
import com.ecar.api.service.order.OrderService;
import com.ecar.api.support.dto.Constants;
import com.ecar.api.support.dto.DriverDto;
import com.ecar.api.support.util.Helper;
import com.ecar.api.support.util.OrderUtil;
import com.ecar.api.support.util.UuidUtils;
import com.ecar.api.support.util.WilddogUtil;
import com.ecar.common.annotation.ResponseFilter;
import com.ecar.common.dto.DataBean;
import com.ecar.common.exception.MyException;
import com.ecar.common.util.BeanUtils;
import com.ecar.common.util.JSONUtil;
import com.ecar.common.util.StringUtil;
import com.ecar.core.driver.entity.Car;
import com.ecar.core.driver.entity.Complaint;
import com.ecar.core.driver.entity.Driver;
import com.ecar.core.driver.entity.Idea;
import com.ecar.core.driver.entity.ModelSet;
import com.ecar.core.order.entity.Order;
import com.ecar.core.order.entity.OrderPriceDetail;
import com.ecar.core.passenger.dao.PaymentCommentMapper;
import com.ecar.core.passenger.entity.PaymentComment;

import net.sf.json.JSONObject;

/**
 * 类DriverController.java的实现描述：实现司机端相关业务处理
 * 
 * @author fire 2017-10-20
 */
@Controller
@Scope("prototype")
@Path("/driver")
public class DriverController extends AbstractResource{
	@Autowired
	FlightService flightService;
	
	@Autowired
	CarService carService;
	
	@Autowired
	OrderPriceDetailService orderPriceDetailService;
	
	@Autowired
	DriverService driverService;
	
	@Autowired
	ModelSetService modelSetService;
	
	@Autowired
	OrderService orderService;
	
	@Autowired
	ComplaintService complaintService;
	
	@Autowired
	IdeaService ideaService;
	
	@Autowired
	PriceCalculateService priceCalculateService;
	
	@Autowired
	PaymentCommentMapper paymentCommentMapper;
	
	/**
	 * 司机确认订单支付
	 * @author fire
	 */
	@POST
	@Path("/finishOrder")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean driverPay(JSONObject param) {
		if (!parse(param) || this.fields == null) return new DataBean(400, new JSONObject(),"请求参数格式错误！");
		if(!this.fields.has("orderNum")||!this.fields.has("driverId")){
			return new DataBean(400,new JSONObject(),"订单号，司机id不能为空");
		}
		String orderNum=this.fields.getString("orderNum");
		String driverId=this.fields.getString("driverId");
		Order order=orderService.selectByOrderNum(orderNum);
		if(order==null||order.getOrderStatus()!=6||order.getOrderType()==7){
			return new DataBean(400,new JSONObject(),"订单号有误");
		}else if(!order.getDriverId().equals(driverId)){
			return new DataBean(400,new JSONObject(),"该司机无权修改此订单");
		}else if(order.getPayStatus()==2){
			return new DataBean(666,new JSONObject(),"订单已支付");
		}
		Order temp=new Order();
		temp.setOrderNum(orderNum);
		temp.setPayStatus(2);
		//添加字段标注为司机手动确认支付的(1:司机确认支付)
		temp.setIsDriver(1);
		
		int i=orderService.updateByOrderNumSelective(temp);
		PaymentComment paymentComment=new PaymentComment();
		paymentComment.setDriverId(driverId);
		paymentComment.setCreateTime(new Date());
		paymentComment.setOrderNo(orderNum);
		paymentComment.setUserId(order.getPassengerId().toString());
		paymentComment.setPayStatus(1);
		paymentComment.setId(UuidUtils.getUUID());
		int ii=paymentCommentMapper.insertSelective(paymentComment);
		
		if(i==1&&ii==1){
			WilddogUtil.removePassengerOrder(orderNum);
			return new DataBean(200,new JSONObject(),"确认订单已支付成功");
		}
		return new DataBean(500,new JSONObject(),"确认订单已支付失败");
	}
	
	
	
	/**
	 * 司机注册
	 * @author fire
	 * @param 
	 */
	@ResponseFilter(target = DriverDto.class, fields = {})
	@POST
	@Path("/reg")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean insert(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) return new DataBean(400, new JSONObject(),"请求参数格式错误！");
			
			log.info("司机用户注册：" + this.fields.toString());
			//获取用户ip 有bug
			//String ip = HttpUtils.getRemoteHost(request);		
			return driverService.regist(fields);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONObject(),"添加用户失败。");
		}
	}
	/**
	 * 司机登陆
	 * @author fire
	 * @param 
	 */
	//过滤除user以外的字段
	@ResponseFilter(target = DriverDto.class, fields = {})
	@POST
	@Path("/login")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean loginWithCaptcha(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) return new DataBean(400,new JSONObject(), "请求参数格式错误！");
			//获取用户ip 有bug
			//String ip = HttpUtils.getRemoteHost(request);		
			return driverService.login(fields);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500,new JSONObject(), "用户登陆失败。");
		}
	}
	/**
	 * 司机用户登出
	 * @author fire
	 * @param 
	 */
	@GET
	@Path("/{driverId}/logout")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean logout(@PathParam("driverId")String driverId) {
		try {
			log.info("司机用户{}登出" ,driverId);
					
			return driverService.logout(driverId);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500,new JSONObject(), "用户登陆失败。");
		}
	}
	/**
	 * 司机端忘记密码,修改密码
	 * @param userId
	 * @param phone
	 * @param captcha
	 * @return
	 */
	@POST
	@Path("/forget")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean forgetPassword(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) return new DataBean(400, new JSONObject(),"请求参数格式错误！");
			if(!this.fields.has("phone")||!this.fields.has("password")){
				return new DataBean(500,new JSONObject(),"手机号，新密码不能为空");
			}
			return driverService.forgetPassword(fields);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500,new JSONObject(),"修改密码失败。");
		}
	}
	
	/**
	 * 接单模式设定
	 * @author fire
	 * 
	 * 
	 * 
	 */
	@POST
	@Path("/settingModelSet")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean settingReceivingModel(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) return new DataBean(400, new JSONObject(),"参数错误，设定接单模式失败。");
			
			ModelSet modelSet = JSONUtil.deserialize(this.fields, ModelSet.class);
			log.info("司机用户：" + modelSet.getDriverId() + ",接单模式设定：" + this.fields.toString());
			Driver driver=driverService.selectByPrimaryKey(modelSet.getDriverId());
			if(driver==null){
				return new DataBean(400,new JSONObject(),"司机id有误");
			}
			
			Integer i=modelSet.getOrderModel();
			if(i==1){
				modelSet.setBeginTime(null);
				modelSet.setEndTime(null);
			}
			if(i==2){
				modelSet.setDestination(null);
			}
			
			if(i!=1){
				if(!this.fields.has("beginTime")||!this.fields.has("endTime")){
					return new DataBean(400,new JSONObject(),"预约时间不能为空");
				}
				if(new Date().after(modelSet.getEndTime())){
					return new DataBean(400, new JSONObject(),"结束时间不得晚与当前时间，请重新输入时间");
				}
			}
			if(i!=2){
				if(!this.fields.has("destination")){
					return new DataBean(400,new JSONObject(),"目的地不能为空");
				}
			}
			
			//该方法里写了判断用户是否已设置接单模式
			boolean b = modelSetService.InsertModelSet(modelSet);
			if(b==true){
				return new DataBean(200, new JSONObject(),"设置成功");
			}
			else{
				return new DataBean(500,new JSONObject(), "设置失败");
			}
		} catch (Exception e) {
			log.info("司机用户: {}，接单模式设定失败: {}", this.fields.getString("driverId"), e.getMessage());
			if (e instanceof MyException) {
				return new DataBean(500, new JSONObject(),e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500, new JSONObject(),"接单模式设定失败，服务器异常。");
			}
		}
	}
	
	/**
	 * 行程状态接口  4:到达上车点5:开始行程6:结束行程
	 * @author fire
	 * 
	 * 
	 * 
	 */
	
	@ResponseFilter(target = Order.class, fields = {})
	@POST
	@Path("/orderStatus")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean updateOrderStatus(JSONObject param) {
		if (!parse(param) || this.fields == null) return new DataBean(400, new JSONObject(),"参数错误，行程状态设置失败。");
		String driverId=fields.getString("driverId");
		int orderStatus=fields.getInt("orderStatus");
		String orderNum=fields.getString("orderNum");
		double emptyDriverDistance=0.0;
		double roadDistance=0.0;
		double addCharge=0.0;
		int driverTime=0;
		if(this.fields.has("driverTime")){
			driverTime=fields.getInt("driverTime");
		}
		if(this.fields.has("emptyDriverDistance")){
			emptyDriverDistance=fields.getDouble("emptyDriverDistance");
		}
		if(this.fields.has("roadDistance")){
			roadDistance=fields.getDouble("roadDistance");
		}
		if(this.fields.has("addCharge")){
			addCharge=fields.getDouble("addCharge");
			if(addCharge<0){
				return new DataBean(200, new JSONObject(), "附加费不能为负值！");
			}
		}
		Order order=orderService.selectByOrderNum(orderNum);
		if(order==null){
			return new DataBean(400, new JSONObject(), "无此订单，请检查您输入的订单号！");
		}
		log.info("司机用户：" + driverId + ",订单状态：" + orderStatus+",订单号"+orderNum);
		try {
			if(order.getOrderStatus()>=orderStatus && order.getOrderStatus()!=7 ){//验证是否重复提交订单状态
				return new DataBean(400, new JSONObject(), "传入的订单状态值异常或重复调接口！");
			}
			if(orderStatus==Constants.END_ROAD){
				if(order.getOrderType()==5){
					if(order.getPcType()==0){
						List<Order> orderList=orderService.selectOrderByParentOrder(order.getParentOrder());
						OrderPriceDetail orderPriceDetail=new OrderPriceDetail();
						orderPriceDetail.setDriverId(order.getDriverId());
						orderPriceDetail.setPassengerId(order.getPassengerId()+"");
						orderPriceDetail.setOrderNum(order.getOrderNum());
						//行程用时
						Calendar endDate=Calendar.getInstance();
						Calendar startDate=Calendar.getInstance();
						startDate.setTime(order.getStartTime());
						endDate.setTime(new Date());
						long timeStart=startDate.getTimeInMillis();
						long endStart=endDate.getTimeInMillis();
						int roadTime=(int)(endStart-timeStart)/(1000*60);
						
						orderPriceDetail.setDriverTime(roadTime);
						int orderSize=orderList.size();
						if(orderSize==0){
							log.info("查询拼车单失败");
						}
						for(Order temporder:orderList){
							if(temporder.getOrderStatus()==1){
								orderSize--;
							}
						}
						if(orderSize>1){//拼单成功
							
							orderPriceDetailService.deleteByOrderNumAndIsSuccess(orderNum, Constants.SHARE_CAR_ISFAIL);//删除拼车失败
							orderPriceDetailService.updateByOrderNumSelective(orderPriceDetail);
							OrderPriceDetail orderPriceDetailQuery=orderPriceDetailService.selectByOrderNum(orderNum);//仅剩一条
							// 更新订单表数据
							int num = orderService.updateByOrderNum(orderNum, new Date(),
								Constants.END_ROAD, orderPriceDetailQuery.getTotalPrice(),Order.ST.CREATED.val());
						}else{
							orderPriceDetailService.deleteByOrderNumAndIsSuccess(orderNum, Constants.SHARE_CAR_ISSUCCESS);
							orderPriceDetailService.updateByOrderNumSelective(orderPriceDetail);
							OrderPriceDetail orderPriceDetailQuery=orderPriceDetailService.selectByOrderNum(orderNum);
							// 更新订单表数据
							int num = orderService.updateByOrderNum(orderNum, new Date(),
									Constants.END_ROAD, orderPriceDetailQuery.getTotalPrice(),Order.ST.CREATED.val());
						}
						//fire给司机排序拼车单
						log.info("司机修改行程状态的时候排序");
						List<Order> list = orderService.selectOrderByParentOrder(orderService.selectByOrderNum(orderNum).getParentOrder());
						for(int i=0;i<list.size();i++){
							if(list.get(i).getOrderStatus()==6 || list.get(i).getOrderStatus()==1){
								list.remove(i);
								i--;
								continue;
							}
							/*if(list.get(i).getOrderNum().equals(orderNum)){
								list.remove(i);
								i--;
								continue;
							}*/
						}
						OrderUtil.sortOrder(list);
						
						//fire 修改野狗的订单状态
						HashMap<String, Object> map=new HashMap<String, Object>();
						order.setOrderStatus(orderStatus);
						Driver driver=driverService.selectByPrimaryKey(driverId);
						map=orderService.sendToPassenger(order, driver);
						WilddogUtil.sendOrderToPassenger(orderNum, map);
						
						map=orderService.sendToDriver(order, driver, 2, "");
						WilddogUtil.getDriverRef("WilddogLocation/order").child(driverId).child("now").updateChildren(map);
						//结束行程后，需要修改司机的可接单模式
						driverService.startGetOrder(driverId);
						return new DataBean(200, new JSONObject(), "订单结束行程设置成功");
					}else{//1:接送机一口价接机,2:接送机一口价送机
						List<Order> orderList=orderService.selectOrderByParentOrder(order.getParentOrder());
						OrderPriceDetail orderPriceDetail=new OrderPriceDetail();
						orderPriceDetail.setDriverId(order.getDriverId());
						orderPriceDetail.setOrderNum(order.getOrderNum());
						//行程用时
						Calendar endDate=Calendar.getInstance();
						Calendar startDate=Calendar.getInstance();
						startDate.setTime(order.getStartTime());
						endDate.setTime(new Date());
						long timeStart=startDate.getTimeInMillis();
						long endStart=endDate.getTimeInMillis();
						int roadTime=(int)(endStart-timeStart)/(1000*60);
						orderPriceDetail.setDriverTime(roadTime);
						orderPriceDetail.setTotalPrice(order.getOrderPrice());
						orderPriceDetail.setId(UuidUtils.getUUID());
						orderPriceDetailService.insertSelective(orderPriceDetail);
						
						// 更新订单表数据
						int num = orderService.updateByOrderNum(orderNum, new Date(),
							Constants.END_ROAD,order.getOrderPrice(),Order.ST.CREATED.val());
						
						//fire给司机排序拼车单
						log.info("司机修改行程状态的时候排序");
						List<Order> list = orderService.selectOrderByParentOrder(orderService.selectByOrderNum(orderNum).getParentOrder());
						for(int i=0;i<list.size();i++){
							if(list.get(i).getOrderStatus()==6 || list.get(i).getOrderStatus()==1){
								list.remove(i);
								i--;
								continue;
							}
							if(list.get(i).getOrderNum().equals(orderNum)){
								list.remove(i);
								i--;
								continue;
							}
						}
						OrderUtil.sortOrder(list);
						
						//fire 修改野狗的订单状态
						HashMap<String, Object> map=new HashMap<String, Object>();
						order.setOrderStatus(orderStatus);
						Driver driver=driverService.selectByPrimaryKey(driverId);
						map=orderService.sendToPassenger(order, driver);
						WilddogUtil.sendOrderToPassenger(orderNum, map);
						
						map=orderService.sendToDriver(order, driver, 2, "");
						WilddogUtil.getDriverRef("WilddogLocation/order").child(driverId).child("now").updateChildren(map);
						//结束行程后，需要修改司机的可接单模式
						driverService.startGetOrder(driverId);
						
						
						return new DataBean(200, new JSONObject(), "订单结束行程设置成功");
					}
					
					
				}else{
					DataBean dataBean=priceCalculateService.getReceiveOrSendOrderPriceDetail(orderNum, emptyDriverDistance, roadDistance,driverTime,addCharge);//
					//fire 修改野狗的订单状态
					if(dataBean.getCode()==200){
						HashMap<String, Object> map=new HashMap<String, Object>();
						order.setOrderStatus(orderStatus);
						Driver driver=driverService.selectByPrimaryKey(driverId);
						map=orderService.sendToPassenger(order, driver);
						WilddogUtil.sendOrderToPassenger(orderNum, map);
						map=orderService.sendToDriver(order, driver, 2, "");
						WilddogUtil.getDriverRef("WilddogLocation/order").child(driverId).child("now").updateChildren(map);
						//结束行程后，需要修改司机的可接单模式
						driverService.startGetOrder(driverId);
					}
					return dataBean;
				}
				//上面是结束订单的逻辑
			}else{
				int count = orderService.updateByDriverId(orderStatus,orderNum);//orderStatus传入值代表意思  4:到达上车点5:开始行程
				if(count>0){
					//fire给司机排序拼车单
					//到达上车点不排序
					//fire 修改野狗的订单状态
					HashMap<String, Object> map=new HashMap<String, Object>();
					order.setOrderStatus(orderStatus);
					Driver driver=driverService.selectByPrimaryKey(driverId);
					map=orderService.sendToPassenger(order, driver);
					WilddogUtil.sendOrderToPassenger(orderNum, map);
					map=orderService.sendToDriver(order, driver, 2, "");
					if(map==null){
						return new DataBean(500,new JSONObject(),"行程状态设置失败，乘客资料已清空");
					}
					Map<String, Object> result=(Map<String, Object>) map.get(orderNum);
					result.put("carpool", orderNum);
					map.put(orderNum, result);
					WilddogUtil.getDriverRef("WilddogLocation/order").child(driverId).child("now").updateChildren(map);
					if(orderStatus==5){
						log.info("司机修改行程状态的时候排序");
						List<Order> list = orderService.selectOrderByParentOrder(orderService.selectByOrderNum(orderNum).getParentOrder());
						OrderUtil.sortOrder(list);
						if(list.size()==1){
							HashMap<String, Object> resultMap=new HashMap<String, Object>();
							resultMap.put("carpool", orderNum);
							WilddogUtil.sendSortDriver(list,list.get(0).getDriverId(), resultMap);
						}
					}
					return new DataBean(200, new JSONObject(),"行程状态设置成功");
				}
				else{
					return new DataBean(500,new JSONObject(), "行程状态设置失败");
				}
			}
		} catch (Exception e) {
			
			log.info("行程状态设置失败: {}", e.getMessage());
			if (e instanceof MyException) {
				return new DataBean(500, new JSONObject(),e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500, new JSONObject(),"行程状态设置失败，服务器异常。");
			}
		}
		
	}
	/**
	 * 司机申诉
	 * @author fire
	 * 
	 * 
	 * 
	 */
	@ResponseFilter(target = ModelSet.class, fields = {})
	@POST
	@Path("/complaint")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean complaint(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) return new DataBean(400, new JSONObject(),"参数错误，设定接单模式失败。");
			if(!this.fields.has("driverId")||!this.fields.has("complaintContent")){
				return new DataBean(500,new JSONObject(),"参数不能为空");
			}
			Complaint complaint = JSONUtil.deserialize(this.fields, Complaint.class);
			log.info("司机用户：" + complaint.getDriverId() + ",申诉：" + this.fields.toString());
			
			return complaintService.insert(complaint);
			
		} catch (Exception e) {
			log.info("司机用户: {}，申诉失败: {}", this.fields.getString("driverId"), e.getMessage());
			if (e instanceof MyException) {
				return new DataBean(500, new JSONObject(),e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500, new JSONObject(),"司机申诉失败，服务器异常。");
			}
		}
	}
	
	/**
	 * 司机个人资料
	 * @author fire
	 * @param 
	 */
	@ResponseFilter(target = Driver.class, fields = {})
	@GET
	@Path("/{driverId}/personInfo")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean insert(@PathParam("driverId") String driverId) {
		try {
			Driver driver=driverService.selectByPrimaryKey(driverId);
			if(driver==null){
				log.info("司机id有误");
				return new DataBean(500, new JSONObject(),"司机个人资料查询失败。");
			}
			driver.setPassword("");
			return new DataBean(200, driver,"司机个人资料查询成功");
		} catch (Exception e) {
			log.info("司机个人资料查询失败: {}", e.getMessage());
			if (e instanceof MyException) {
				return new DataBean(500, new JSONObject(),e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500, new JSONObject(),"司机个人资料查询失败，服务器异常。");
			}
		}
	}
	
	/**
	 * 司机个人资料提交
	 * @author fire
	 * @param 
	 */
	@ResponseFilter(target = Driver.class, fields = {})
	@POST
	@Path("/insertPersonInfo")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean insertPersonInfo(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null)
				return new DataBean(400, new JSONObject(),"请求参数格式错误！");
			if(!this.fields.has("id")){
				return new DataBean(400,new JSONObject(),"id不能为空");
			}
			
			log.info("司机{}个人资料提交：",this.fields.getString("id"));
			Driver driver = driverService.selectByPrimaryKey(this.fields.getString("id"));
			if (driver == null) return new DataBean(404, "用户未找到，修改失败。");
			Driver result=new Driver();
			result.setId(driver.getId());
			
			
			boolean success = false;
			if(this.fields.has("avatar")){
				String avatar = this.fields.getString("avatar");
				if (StringUtil.isNotEmpty(avatar) && avatar.startsWith("base64://")) {
					avatar = avatar.substring(9);
					avatar = Helper.uploadBase64Avatar(avatar);
					if (StringUtil.isNotEmpty(avatar)) {
						result.setAvatar(avatar);
						success = true;
					}
					if(!success){
						return new DataBean(400,new JSONObject(),"头像上传失败。");
					}
					result.setAvatar(avatar);
				}
			}
			if(this.fields.has("selfIntroduction")){
				String selfIntroduction = this.fields.getString("selfIntroduction");
				result.setSelfIntroduction(selfIntroduction);
			}
			if(this.fields.has("name")){
				String name = this.fields.getString("name");
				result.setName(name);
			}
			return driverService.updateByPrimaryKeySelective(result);
		} catch (Exception e) {
			log.info("司机个人资料提交失败: {}", e.getMessage());
			if (e instanceof MyException) {
				return new DataBean(500,new JSONObject(), e.getMessage());
			} else {
				e.printStackTrace();
				return new DataBean(500, new JSONObject(),"司机个人资料提交失败，服务器异常。");
			}
		}
	}
	
	
	
	
	/**
	 * txp
	 * 司机端获取每天接单量,服务分,总金额
	 * 
	 * @param driverId
	 * @return
	 */
	@GET
	@Path("/{driverId}/orderDetail")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean getOrderDetail(@PathParam("driverId") String driverId) {
		try {
			int i = orderService.queryOrderCountByDriverId(driverId);
			Double totalPrice = orderService.queryTotalPrice(driverId);
			if (totalPrice==null) {
				totalPrice=0.0;
			}
			Map<String, Object> map = new HashMap<>();
			map.put("count", i);
			map.put("totalPrice", totalPrice);
			
			Driver driver = driverService.selectByPrimaryKey(driverId);
			long rates =0;
			if (driver == null) {
				return new DataBean(404, new JSONObject(), "司机ID错误!");
			} else {
				Integer status = driver.getStatus();
				Double rates2 = driver.getRates();
				if (status==null) {
					status=0;
				}
				if (rates2==null) {
					rates2=0.0;
				}
				rates = Math.round(rates2*20);
				
				map.put("status", status);
				map.put("rates", rates);
			}
			return new DataBean(200, map, "查询成功返回司机每日订单数量和总金额和服务分!");
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONObject(), "服务器错误!");
		}
	}
	
	/**
	 * txp
	 * 司机端开始接单;
	 * 
	 * @param driverId
	 * @return
	 */
	@GET
	@Path("/{driverId}/startGetOrder")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean startGetOrder(@PathParam("driverId") String driverId) {
		try {
			
			DataBean bean = driverService.startGetOrder(driverId);
			
			return bean;
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONObject(), "服务器错误!");
		}
	}
	
	/**
	 * @author fire
	 * 司机端抢单;
	 * 
	 * @param driverId
	 * @return
	 */
	@POST
	@Path("/grabOrder")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean grabOrder(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) return new DataBean(400, new JSONObject(),"请求参数格式错误！");
			if(!this.fields.has("orderNum")||!this.fields.has("driverId")){return new DataBean(500,new JSONObject(),"订单号和司机id不能为空");}
			Order order=JSONUtil.deserialize(this.fields, Order.class);
			return orderService.grabOrder(order);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONObject(), "服务器错误!");
		}

	}
	
	/**
	 * txp
	 * 司机端停止接单;
	 * 
	 * @param driverId
	 * @return
	 */
	@GET
	@Path("/{driverId}/stopGetOrder")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean stopGetOrder(@PathParam("driverId") String driverId) {
		try {
			
			DataBean bean = driverService.stopGetOrder(driverId);
			
			return bean;
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500,new JSONObject() , "服务器错误!");
		}

	}
	/**
	 * 司机意见反馈
	 * @author fire
	 * @param 
	 */
	//过滤除user以外的字段
	@ResponseFilter(target = Idea.class, fields = {})
	@POST
	@Path("/idea")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean submitIdea(JSONObject param) {
		try {
			if (!parse(param) || this.fields == null) return new DataBean(400,new JSONObject(), "请求参数格式错误！");
			log.info("司机:{},意见反馈：{}" , this.fields.getString("driverId") ,this.fields.toString());
			
			Idea idea = JSONUtil.deserialize(this.fields, Idea.class);
				
			return ideaService.insert(idea);
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500,new JSONObject(), "用户登陆失败。");
		}
	}
	
	/**
	 * txp
	 * 司机端获取每天接单量和总金额
	 * 
	 * @param driverId
	 * @return
	 */
	@GET
	@Path("/{driverId}/wallet/balance")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean getBlance(@PathParam("driverId") String driverId) {
		try {
			Driver driver = driverService.selectByPrimaryKey(driverId);
			if (driver == null) {
				return new DataBean(404, new JSONObject(), "司机ID错误!");
			} 
			Double totalPrice = orderService.queryTotalPrice(driverId);
			Double blance = orderPriceDetailService.queryBlance(driverId);
			if (totalPrice==null) {
				totalPrice=0.0;
			}
			if (blance==null) {
				blance=0.0;
			}

			
			Map<String, Object> map = new HashMap<>();
			map.put("totalPrice", totalPrice);
			map.put("blance", blance);
			
			
			return new DataBean(200, map, "查询成功返回司机钱包余额和今日订单金额");
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONObject(), "服务器错误!");
		}
	}
	
	
	
	/**
	 * txp
	 * 司机获取机场俩小时出发人数和到达人数
	 * 
	 * @param driverId
	 * @return
	 */
	@GET
	@Path("/{driverId}/flight/personNo")
	@Produces(MediaType.APPLICATION_JSON)
	public DataBean getFlight(@PathParam("driverId") String driverId) {
		try {
			Driver driver = driverService.selectByPrimaryKey(driverId);
			if (driver == null) {
				return new DataBean(404, new JSONObject(), "司机ID错误!");
			} 
			
			Map <String,Object>map =  new HashMap<>();
			
			Car car = carService.selectCarByDriverId(driverId);
			String numberPlate = car.getNumberPlate();
			String model = car.getModel();
			String pictureAddress = car.getPictureAddress();
			String remark = car.getRemark();
			map.put("model", model);//车型
			map.put("numberPlate", numberPlate);//牌照
			map.put("pictureAddress", pictureAddress);//图片地址
			map.put("remark", remark);//备注
			 
			Date date1 = new Date(System.currentTimeMillis()-(2000*60*60));
			Date date2 = new Date(System.currentTimeMillis());
			System.out.println(date1);
			System.out.println(date2);
			Integer goNum= flightService.queryGoPersonNum(date1,date2);
			Integer arriveNum = flightService.queryArrivePersonNum(date1,date2);
			if (goNum==null) {
				goNum=0;
			}
			if (arriveNum==null) {
				arriveNum=0;
			}
			map.put("goNum", goNum);
			map.put("arriveNum", arriveNum);
			
			return new DataBean(200, map, "查询成功返回车辆信息和机场两小时出入人数");
		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(500, new JSONObject(), "服务器错误!");
		}
	}
	
}


